<?php

namespace App\Http\Controllers\Home\Wechat;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
//use App\Http\Controllers\Controller;
use App\Models\wechat\OrderAddress,App\Models\wechat\OrderProduct;
use App\Models\wechat\Carts,App\Models\shop\Product,App\Models\shop\Customer;
use App\Models\wechat\Address;
use App\Models\wechat\Order;
use EasyWeChat\Payment\Order as WechatOrder;
use EasyWeChat;


class OrderController extends CommonController
{
    function __construct()
    {
        parent::__construct();
    }

    //下单
    public function checkout()
    {
//        return $this->customer;
        $carts = Carts::with('product')->where('customer_id', $this->customer->id)->get();
//        return $carts;
        //如果购物车中没有商品,跳回购物车页面
        if ($carts->isEmpty()) {
            return redirect('/wechat/carts/index');
        }

        $address=Address::find($this->customer->address_id); //默认收获地址 从session中获取customer里存储的address_id
//        return $address;
        return view('home.wechat.order.checkout')
            ->with('carts',$carts)
            ->with('count',Carts::count_carts($carts))
            ->with('address',$address);
    }


    //
    public function index(Request $request)  //test
    {
        //多条件查找
        $where = function ($query) use ($request) {
            $query->where('customer_id', $this->customer->id);

            switch ($request->status) {
                case '':
                    break;
                case '1':
                    $query->where('status', 1);
                    break;
                case '2':
                    $query->whereIn('status', [2, 3, 4]);
                    break;
            }
        };

        $order_status = config('fangshop.order_status');
        $orders = Order::where($where)->with('order_products.product', 'customer', 'address')
            ->orderBy('created_at', 'desc')
            ->get();
//        return $orders;
        return view('home.wechat.order.index')
            ->with('orders', $orders)
            ->with('order_status', $order_status);
    }

    public function store(Request $request)  //生成订单  orders order_products order_address
    {
        $count = Carts::count_carts();
//        return $count;
        $total_price = $count['totalPrice'];
        $data = [];

        DB::beginTransaction();
        try {
           //生成订单
            $order = Order::create([
                'customer_id' => $this->customer->id,
                'total_price' => $total_price,
                'status' => 1
            ]);


            //生成订单地址
        /**
         * 之前每个用户创建地址的时候，有插入address表，这里搞个order_address  是因为一个用户有多个地址，但一个订单只有一个地址
         */
            $address=Address::find($request->address_id);  //从地址表中通过地址id 找到对应地址数据 下一步插入订单地址表中
            $order->address()->create([
                'province' => $address['province'],
                'city' => $address['city'],
                'area' => $address['area'],
                'detail' => $address['detail'],
                'name' => $address['name'],
                'tel' => $address['tel'],
            ]);


            //查询出购物车中的所有商品
            $carts=Carts::with('product')->where('customer_id',$this->customer->id)->get();
//            return $carts;
            foreach ($carts as $cart)
            {
                //判断库存是否足够
                if($cart->product->stock != '-1' and $cart->product->stock - $cart->num < 0)
                {
                    throw new \Exception('商品' . $cart->product->name . ", 目前仅剩下" . $cart->product->stock . " 件. \n请返回购物车, 修改订单后再下单!");
                }

                //削减库存数量
                if ($cart->product->stock != '-1') {
                    $cart->product->decrement('stock', $cart->num);
                }


                //插入订单商品表
                $order->order_products()->create([
                    'product_id' => $cart->product_id,
                    'num' => $cart->num
                ]);
            }

            //清空购物车
            Carts::with('product')->where('customer_id', $this->customer->id)->delete();

        } catch (\Exception $e) {
            //echo $e->getMessage();

            DB::rollback();
            $data['status'] = 0;
            $data['info'] = $e->getMessage();
            return $data;
        }
        DB::commit();


        $data['status'] = 1;
        $data['order_id'] = $order->id;
        return $data;
    }

    public function show_pay($id) //生成订单成功后 跳转到微信支付页面
    {

        $order = Order::with('address')->find($id);

        //计算总价格, 以分为单位, 所以: *100
        $total_fre = ($order->total_price + $order->express_money) * 100;

        /**
         * 第 2 步：创建订单
         */
        $attributes = [
            'openid' => $this->customer->openid,
            'body' => '订单号:' . $order->id,
            'detail' => 'yaofei小卖部',
            'out_trade_no' => $order->id,
            'total_fee' => $total_fre,
            'trade_type' => 'JSAPI',
            'notify_url' => 'http://wechat.52nodejs.com/shop/order/order_notify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
        ];
        $wechat_order = new WechatOrder($attributes);

        /**
         * 第 3 步：统一下单
         */
        $payment = EasyWeChat::payment();
        $result = $payment->prepare($wechat_order);
        $prepayId = $result->prepay_id;
        $json = $payment->configForPayment($prepayId);

        return view('home.wechat.order.show_pay')->with('order', $order)->with('json', $json);
    }


    public function show($id)  //我的订单
    {
        $order = Order::with('address', 'express', 'customer', 'order_products.product')->find($id);
        return view('home.wechat.order.show')->with('order', $order);
    }
    public function destroy($id)  //删除订单   //传参 order_id
    {
        //查出对应的商品,并将库存还回去
        $order = Order::with('order_products')->find($id);
//        return $order;
        foreach ($order->order_products as $order_product) {
            $product = Product::find($order_product->product_id);
            //如果不是无限库存 把该商品的库存增加订单里的商品数量
            if ($product->stock != '-1') {
                Product::where('id', $order_product->product_id)->increment('stock', $order_product->num);
            }
        }

        //删除订单商品
        OrderProduct::where('order_id', $id)->delete();
        //删除订单地址
        OrderAddress::where('order_id', $id)->delete();
        Order::destroy($id);
        return redirect('/wechat/customer/index');
    }
}
